
package com.kingcat.smartchair.webview;

import android.app.Activity;
import android.content.*;
import android.os.Build;
import android.util.*;
import android.webkit.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kingcat.smartchair.MainActivity;
import com.kingcat.smartchair.R;
import com.kingcat.smartchair.SmartDatabaseHelper;
import com.kingcat.smartchair.utils.AppUtils;
import com.kingcat.smartchair.utils.AutoUpdateTask;
import com.kingcat.smartchair.utils.DeviceUt;
import com.kingcat.smartchair.utils.Tools;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by guoshuyu on 2017/6/16.
 */

public class SmartChairWebView extends WebView {

    // 使用WEBVIEW的父活动
    private Activity mActivity;

    // 日志TAG
    static String TAG = "SmartChairWebView";

    public SmartChairWebView(Context context) {
        super(context);
    }

    public SmartChairWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SmartChairWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    // 设置属性
    public void setAttr(Activity activity)
    {
        mActivity = activity;

        // 清除缓存
        this.clearCache(true);
        this.clearHistory();

        // // 清除自动完成填充的表单数据
        this.clearFormData();

        // 打开调试模式
        this.setWebContentsDebuggingEnabled(true);

        // 关闭调试模式
        //this.setWebContentsDebuggingEnabled(false);

        //支持js
        this.getSettings().setJavaScriptEnabled(true);

        // 保持活动 防止进入后台后JS停止运行
        this.setKeepScreenOn(true);

        // 启用 Local Storage
        this.getSettings().setDomStorageEnabled(true);

        // 当设置为true，就可以 使用file://加载文件
        this.getSettings().setAllowFileAccess(true);

        // 禁用缓存
        this.getSettings().setAppCacheEnabled(false);
        this.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        //设置自适应屏幕，两者合用
        this.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        this.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        // 允许混用HTTP HTTPS
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
           this.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        // 视频自动播放
        this.getSettings().setMediaPlaybackRequiresUserGesture(false);


        // 设置WebViewClient 处理各类时间和通知
        SmartChairWebViewClient client = new SmartChairWebViewClient();
        client.setActivity(mActivity);
        this.setWebViewClient(client);

        //链接js注入接口
        this.linkJSInterface();

        // 禁用缩放
        this.getSettings().setBuiltInZoomControls(false);
        this.getSettings().setDisplayZoomControls(false);
        this.getSettings().setSupportZoom(false);

        // 延迟1秒加载url
        final WebView temp = this;
        this.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 设备号
                String udid = DeviceUt.GetUDID(AppUtils.getAppContext());

                //Log.e(TAG, "页面启动...");
                //Toast.makeText(mActivity, "Click strType: " + udid + "。\n\nValue: " + udid, Toast.LENGTH_LONG).show();

                temp.loadUrl("file:///android_asset/index.html?udid=" + udid);
            }
        }, 1000);
    }

    // 设置被web调用的接口类实例
    public void linkJSInterface() {
        this.addJavascriptInterface(new ActionSelectInterface(this), "JSInterface");
    }

    /**
     * js选中的回掉接口
     */
    private class ActionSelectInterface {

        SmartChairWebView mContext;

        ActionSelectInterface(SmartChairWebView c) {
            mContext = c;
        }

        @JavascriptInterface
        public String callback(final String strType, final String value) {

            Log.e("-----------js", "strType:" + strType);
            Log.e("-----------js", "value:" + value);
            //Toast.makeText(mActivity, "udid: " + udid, Toast.LENGTH_LONG).show();

            // 升级APP
            if(strType.equals("update"))
            {
                //((MainActivity)mActivity).Update();
                return "";
            }

            // 升级APP文件大小
            if(strType.equals("getupdateappsize"))
            {
                return String.valueOf(AppUtils.getApkSize());
            }

            // 升级APP已下载大小
            if(strType.equals("getupdateappdownloadsize"))
            {
                return String.valueOf(AppUtils.getApkDownloadSize());
            }

            // 自动升级APP
            if(strType.equals("startupdate"))
            {
                // 升级组件包名
                String packageName = "com.kingcat.smartchairupdate";

                AtomicBoolean hasInstallUpdate  = new AtomicBoolean(false);
                List<Map<String, Object>> apps = DeviceUt.getInstalledApps(AppUtils.getAppContext());
                apps.forEach(app ->{
                    String temp = app.get("package_name").toString();
                    if(packageName.equals(temp))
                    {
                        hasInstallUpdate.set(true);
                    }
                });

                // 已安装
                if(hasInstallUpdate.get())
                {
                    // 检测是否安装升级组件
                    if(value.equals("checkupdateapp"))
                    {
                        return "ok";
                    }

                    // 升级主程序
                    if(value.equals("updatemain"))
                    {
                        // 打开升级组件开始升级主程序
                        DeviceUt.openPackage(AppUtils.getAppContext(),packageName);
                        return "ok";
                    }

                    return "ok";
                }

                // 未安装则先安装升级组件
                try{
                    // 先安装升级组件
                    AutoUpdateTask task = new AutoUpdateTask(mActivity, AppUtils.getAppContext());
                    task.CheckUpdate();
                    return "ok";
                }
                catch (Exception ex)
                {
                    return "err";
                }
            }

            // 调用设置
            if(strType.equals("setting"))
            {
                String target = "android.settings.APPLICATION_SETTINGS";
                Intent intent = new Intent(target);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                AppUtils.getAppContext().startActivity(intent);
                return "ok";
            }

            // 写入日志
            if(strType.equals("log"))
            {
                Log.e("-----------log", value);
                JSONObject jsonObject = JSON.parseObject(value);
                ContentValues model = new ContentValues();
                model.put("udid", jsonObject.getString("udid"));
                model.put("page", jsonObject.getString("page"));
                model.put("time", jsonObject.getLong("time"));
                model.put("cat", jsonObject.getLong("cat"));
                model.put("event", jsonObject.getString("event"));
                model.put("message", jsonObject.getString("message"));
                SmartDatabaseHelper.AddDeviceLog(AppUtils.getAppContext(), model);

                return "ok";
            }

            // 重启
            if(strType.equals("reboot"))
            {
                DeviceUt.rootCall("reboot");
                return "ok";
            }

            // 关机
            if(strType.equals("close"))
            {
                DeviceUt.rootCall("reboot -p");
                return "ok";
            }

            // 杀死某个APP
            if(strType.equals("killapp"))
            {
                DeviceUt.rootCall("am force-stop " + value);
                DeviceUt.rootCall("ps | grep '" + value + "' | awk '{print $2}' | xargs kill -9");
                return "ok";
            }

            // 获取udid
            if(strType.equals("getudid"))
            {
                String udid = DeviceUt.GetUDID(AppUtils.getAppContext());
                //Toast.makeText(mActivity, "udid: " + udid, Toast.LENGTH_LONG).show();
                return udid;
            }

            // 获取接口地址主机
            if(strType.equals("getapihost"))
            {
                String apihost = "";
                if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
                {
                    apihost = AppUtils.getAppContext().getString(R.string.smartchari_apihost_prod);
                }

                if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
                {
                    apihost = AppUtils.getAppContext().getString(R.string.smartchari_apihost_dev);
                }

                return apihost;
            }

            // 获取版本号
            if(strType.equals("getversion"))
            {
                String version = DeviceUt.GetVersion(AppUtils.getAppContext());
                //Toast.makeText(mActivity, "udid: " + udid, Toast.LENGTH_LONG).show();
                return version;
            }

            // 获取安卓版本号
            if(strType.equals("getsysversion"))
            {
                String version = DeviceUt.GetSysVersion(AppUtils.getAppContext());
                //Toast.makeText(mActivity, "udid: " + udid, Toast.LENGTH_LONG).show();
                return version;
            }

            // 获取APP列表
            if(strType.equals("getapps"))
            {
                List<Map<String, Object>> apps = DeviceUt.getInstalledApps(AppUtils.getAppContext());
                String  res = new Gson().toJson(apps);
                return res;
            }

            // 打开某个APP
            if(strType.equals("openapp"))
            {
                // 只有解锁状态下才能打开APP
                if(AppUtils.getAppIsUnlock())
                {
                    DeviceUt.openPackage(AppUtils.getAppContext(),value);
                }

                return "ok";
            }

            // 打开爱奇艺的频道页
            if(strType.equals("openqiyi"))
            {
                // 只有解锁状态下才能打开APP
                if(AppUtils.getAppIsUnlock())
                {
                    // 打开爱奇艺的频道页
                }

                return "ok";
            }

            // 设置音量
            if(strType.equals("setvolume"))
            {
                DeviceUt.setVolume(AppUtils.getAppContext(),value);
                return "ok";
            }

            // 前端网络异常，杀死所有第三方APP并返回到启动页
            if(strType.equals("networkerr"))
            {
                DeviceUt.killAllApp(AppUtils.getAppContext());

                mContext.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 设备号
                        String udid = DeviceUt.GetUDID(AppUtils.getAppContext());

                        Log.e(TAG, "页面启动...");

                        mContext.loadUrl("file:///android_asset/index.html?udid=" + udid);
                    }
                }, 1000);

                return "ok";
            }

            return null;
        }
    }
}